﻿using CommunityToolkit.Mvvm.ComponentModel.__Internals;
using Dark_Core_Server.Models.File;
using Dark_Core_Server.Models.Universal;
using Dark_Core_Server.Models.User;
using Dark_Core_Server.Service;
using DarkSKL_Core.ArgModules;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MongoDB.Bson;
using MongoDB.Driver;

namespace Dark_Core_Server.Controllers
{
    [Route("CoreService/[controller]:[action]")]
    [ApiController]
    public class FileController : ControllerBase
    {

        private readonly FileService Service;
        private readonly UserService UserService;
        public FileController(FileService service, UserService userService)
        {
            this.Service = service;
            this.UserService = userService;

        }


        //  [FromForm] string[] virtualPaths
        [HttpPost]
        [Authorize]
        [DisableRequestSizeLimit]
        public async Task<ActionResult> Upload([FromForm] IFormFile file)
        {
            ResponseMsg<UserDocument> userResponseMsg = await UserService.ParseHttpRequestToUser(
                HttpContext.Request
            );
            if (userResponseMsg.Status != UniversalState.Success)
                return Ok(false.CreateResponseMsg("User not found", UniversalState.Error));


            var result = await Service.SaveFileAsync(file);
            return Ok(result);
        }

        [HttpPost]
        public async Task<ActionResult> Query(PostRequestArgs args)
        {
            FileQueryMode queryMode = args.mode.ToFileQueryMode();
            args.args.TryGetValue("payload", out var payload);
            if (payload == null) return Ok(false.CreateResponseMsg("缺少参数 payload", UniversalState.Error));
            return Ok(await Service.QueryFileListAsync(queryMode, payload?.ToString()??""));
        }


        [HttpPost]
        [Authorize]
        public async Task<ActionResult> Delete(PostRequestArgs args)
        {
            args.args.TryGetValue("payload", out var payload);
            if (payload == null) return Ok(false.CreateResponseMsg("缺少参数 payload", UniversalState.Error));
            if (!ObjectId.TryParse(payload.ToString(), out var id))
                return Ok(false.CreateResponseMsg("Invalid ObjectID", UniversalState.Error));
            return Ok(await Service.DeleteFileAsync(id));
        }




        // 查询文件引用
        [HttpPost]
        public async Task<ActionResult> QueryReference(PostRequestArgs args)
        {

            FileReferenceQueryMode queryMode = args.mode.ToFileReferenceQueryMode();

            args.args.TryGetValue("payload", out var payload);
            args.args.TryGetValue("secondlyPayload", out var secondlyPayload);
            if (payload == null)
                return Ok(false.CreateResponseMsg("缺少参数 payload(ObjectID ID)", UniversalState.Error));
            if (queryMode is FileReferenceQueryMode.UserIDAndFileName or FileReferenceQueryMode.UserIDAndFileType)
                if (secondlyPayload is null)
                    return Ok(false.CreateResponseMsg("缺少参数 secondlyPayload(文件名或文件类型)", UniversalState.Error));
            return Ok(await Service.QueryReferenceAsync(queryMode,
                new[] { payload?.ToString() ?? "", secondlyPayload?.ToString() ?? "" }));
        }



        // 创建文件引用
        [HttpPost]
        [Authorize]
        public async Task<ActionResult> CreateReference(SimpleFileReferenceRecord record)
        {
            ResponseMsg<UserDocument> userResponseMsg = await UserService.ParseHttpRequestToUser(
                HttpContext.Request
            );
            if (userResponseMsg.Status != UniversalState.Success)
                return Ok(false.CreateResponseMsg("User not found", UniversalState.Error));
            var result = await Service.AddReferenceAsync(userResponseMsg.Data.id, record);
            return Ok(result);


        }
        
        //删除文件引用
        [HttpPost]
        [Authorize]
        public async Task<ActionResult> DeleteReference(PostRequestArgs args)
        {

            // 解析当前用户
            ResponseMsg<UserDocument> userResponseMsg = await UserService.ParseHttpRequestToUser(
                HttpContext.Request
            );
            if (userResponseMsg.Status != UniversalState.Success)
                return Ok(false.CreateResponseMsg("User not found", UniversalState.Error));

            args.args.TryGetValue("payload", out var referenceDocumentId);
            if (referenceDocumentId == null)
                return Ok(false.CreateResponseMsg("缺少参数 payload(文件引用ID)", UniversalState.Error));

            if (!ObjectId.TryParse(referenceDocumentId.ToString(), out var referenceId))
                return Ok(false.CreateResponseMsg("Invalid ObjectID", UniversalState.Error));
            var deleteResult = await Service.RemoveReferenceAsync(userResponseMsg.Data.id, referenceId);
            return Ok(deleteResult);
        }



    }
}
